import { asyncRouterMap,  NotFoundRoutes} from '@/router'

function hasPermission(route, menu) {
  return route.name === menu.name
}

export function filterAsyncRoutes(routes, menus) {
  let res = []
  console.log(res,111)
  routes.forEach(route => {
    const tmp = { ...route }
    menus.forEach(menu => {
      let tmpMenu = { ...menu }
      if (hasPermission(tmp, tmpMenu)) {
        // 优先取出不是菜单也没有嵌套在children里的路由
        let hiddenRoutes = []
        tmp.children && tmp.children.forEach(child => {
          const tmpChild = { ...child }
          if (tmpChild.hidden) {
            hiddenRoutes.push(tmpChild)
          }
        })
        if (tmp.children && tmpMenu.sub) {
          tmp.children = filterAsyncRoutes(tmp.children, tmpMenu.sub)
          if (hiddenRoutes.length) {
            tmp.children = tmp.children.concat(hiddenRoutes)
          }
        }
        console.log(tmp,234)
        res.push(tmp)
      }
    })
  })
  return res
}


function reWriteRedirect (route) {
  let { redirect, path } = route
  if (redirect) {
    if (route.children && route.children.length) {
      for(let i = 0; i < route.children.length; i++) {
        if (!route.children[i].hidden) {
          let subPath = path + '/' + route.children[i].path
          if (redirect !== subPath) {
            route.redirect = subPath
          }
          return false
        }
      }
    }
  }
  return route
}

const state = {
  routes: [],
}

const mutations = {
  SET_ROUTES: (state, routes) => {

    state.routes = routes
    console.log(state.routes,9800)
  }
}

const actions = {
  generateRoutes({ commit }, menu) {
    return new Promise(resolve => {
      console.log(menu,123)
      let accessedRoutes = filterAsyncRoutes(asyncRouterMap, menu)

      console.log(accessedRoutes,1241123)
      // return false;
      // accessedRoutes.forEach(route => {
      //   reWriteRedirect(route)
      //   if (route.children && route.children.length) {
      //     route.children.forEach(subRoute => {
      //       reWriteRedirect(subRoute)
      //     })
      //   }
      // })
      commit('SET_ROUTES', accessedRoutes.concat(NotFoundRoutes))
      resolve(accessedRoutes.concat(NotFoundRoutes))
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
